package com.changgou.order.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.order.config.TokenDecode;
import com.changgou.order.pojo.CartItem;
import com.changgou.order.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URLDecoder;
@Controller
@RequestMapping("/cart")
public class JoinCartController {

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 登录后请求转发到当前页面
     * 合并cookie和redis中购物车数据
     * 返回到登录前页面
     * @param from
     * @return
     */
    @RequestMapping("/joinCart")
    public void joinCart(@RequestParam("from")String from) throws IOException, ServletException {
        String userName = tokenDecode.getUserName();
        //获取cookie中购物车数据
        Cookie[] cookies = request.getCookies();
        if (cookies==null)  return ;
        for (Cookie cookie : cookies) {
            if (cookie.getName().startsWith("Cart_")){
                //获取每一条cookie_cart(cart_开头的数据购物车数据)数据
                String cartJson = URLDecoder.decode(cookie.getValue(), "utf-8");
                CartItem cartItem = JSON.parseObject(cartJson, CartItem.class);
                if (cartItem==null)continue;
                //添加信息
                redisTemplate.boundHashOps("Cart_"+userName).put(cartItem.getSkuId(),cartItem);
                //删除cookie
                CookieUtil.addCookie(response,"192.168.16.172","/",cookie.getName(),"",-1,false);
            }
        }
        ServiceInstance sysgateway = loadBalancerClient.choose("GATEWAY-WEB");
//        URI uri = sysgateway.getUri();
//        request.getRequestDispatcher(uri+from).forward(request,response);
        if (StringUtils.isEmpty(from)){
            response.sendRedirect("http://192.168.16.172:8001"+"");
        }else {
            response.sendRedirect("http://192.168.16.172:8001"+from);
        }
    }

}
